#py_social/networks/Twitter.py
import urllib
import urlparse

import oauth2 as oauth

from py_social.core import register_network
from py_social.core import Credential
from py_social.core import PySocialError
from py_social.core import BaseNetwork
#from py_social import utils

@register_network
class Twitter(BaseNetwork):
    name = 'twitter'

    """Twitter doesn't use scopes"""
    scope_str = ''
    scope_options = {
                     'post': '',
                     'get_friends': '',
                     'default': '',
    }
    """
    """
    auth_url = 'api.twitter.com/oauth/authorize'
    access_token_url = 'api.twitter.com/oauth/access_token'
    request_token_url = 'api.twitter.com/oauth/request_token'

    def new_credential(self, request, oauth_token='', oauth_verifier=''):
        """
        Take a callback request object and return a valid credential object.
        Currently handled request objects:
            Django
        Alternatively you can pass in the oauth_token and oauth_verifier give by Twitter
        """
        consumer = oauth.Consumer(self.pyso_client_id, self.pyso_secret)
        if request:
            oauth_token = request.GET.get('oauth_token', '')
            oauth_verifier = request.GET.get('oauth_verifier', '')

        if not all([oauth_token, oauth_verifier]):
            raise PySocialError("Network Error")

        token = oauth.Token(oauth_token, self.pyso_secret)
        client = oauth.Client(consumer, token)

        resp, content = client.request(self.access_token_url, "POST")
        if resp['status'] != 200:
            raise PySocialError("Network Error - %s" % resp['status'])
        access_token = dict(urlparse.parse_qsl(content))

        cred_dict = {}
        cred_dict['access_token'] = content
        cred_dict['uuid'] = access_token['user_id']
        cred_dict['name_in_network'] = access_token['screen_name'][0]
        cred_dict['network'] = self
        return Credential(cred_dict)


    def get_auth_url(self, touch=False):

        #the first step is a an unauthed 'request' token, the provider will not even deal with us until we have that
        # so we build a request, and sign it,
        consumer = oauth.Consumer(self.pyso_client_id, self.pyso_secret)
        client = oauth.Client(consumer)

        resp, content = client.request(self.request_token_url, "GET")
        if resp['status'] != '200':
            raise Exception("Invalid response %s." % resp['status'])

        request_token = dict(urlparse.parse_qsl(content))

        return "%s?oauth_token=%s" % (self.auth_url, request_token['oauth_token'])

    def post(self, credential, message, **kwargs):
        pass
        #TODO

    def get_friends(self, credentials):
        pass
        #TODO
